package com.sunny.fetch.service;

import com.google.gson.Gson;
import com.sunny.common.pojo.SunResult;
import com.sunny.fetch.common.RequestParam;
import com.sunny.fetch.common.ResultData;
import com.sunny.fetch.mapper.FStockBasicMapper;
import com.sunny.fetch.pojo.FStockBasic;
import com.sunny.fetch.rest.StockBasicApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.List;

@Service
@Slf4j
public class StockBasicService extends BaseService<StockBasicApi> {
    @Autowired
    private FStockBasicMapper stockBasicMapper;

    @Override
    public SunResult execute() {
        StockBasicApi client = getClient();
        RequestParam body = RequestParam
                .builder("stock_basic")
                .setFields(getFieldList("stock_basic"))
                .build();
        client.getStockBasic(body)
                .enqueue(new Callback<ResultData>() {
                    @Override
                    public void onResponse(Call<ResultData> call, Response<ResultData> response) {
                        System.out.println(call);
                        System.out.println("--------------------------");
                        System.out.println(response);
                        Gson gson = new Gson();
                        ResultData resultData = response.body();
                        List<FStockBasic> items = resultData.getItems(FStockBasic.class);
                        //将结果保存至数据库
                        saveData(items);
                    }

                    @Override
                    public void onFailure(Call<ResultData> call, Throwable throwable) {
                        System.out.println(call);
                        throwable.printStackTrace();
                    }
                });

        return SunResult.ok();
    }

    @Transactional
    public void saveData(List<FStockBasic> list) {
        long startTime = System.currentTimeMillis();
        stockBasicMapper.insertList(list);
        //list.forEach(item->stockBasicMapper.insert(item));
        log.debug("插入数据完毕，插入数据条数：" + list.size() + " 持续时长：" + ((System.currentTimeMillis() - startTime) / 1000));
    }


}
